﻿namespace Communergy.Silverlight.Client
{
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Navigation;
    using Communergy.Silverlight.Client.Resources;
    using Communergy.Silverlight.Client.LoginUI;
    using System.Windows.Ria.ApplicationServices;

    public partial class Home : Page
    {
        private readonly AuthenticationService authService = WebContext.Current.Authentication;

        public Home()
        {
            InitializeComponent();

            this.Title = ApplicationStrings.HomePageTitle;

            authService.LoggedIn += new System.EventHandler<AuthenticationEventArgs>(Authentication_LoggedIn);
            authService.LoggedOut += new System.EventHandler<AuthenticationEventArgs>(Authentication_LoggedOut);

            this.UpdateLoginState();
        }

        private void Authentication_LoggedIn(object sender, AuthenticationEventArgs e)
        {
            this.UpdateLoginState();
        }

        private void Authentication_LoggedOut(object sender, AuthenticationEventArgs e)
        {
            this.UpdateLoginState();
        }

        private void UpdateLoginState()
        {
            if (WebContext.Current.User.IsAuthenticated)
            {
                this.AnonymousContent.Visibility = Visibility.Collapsed;
            }
            else
            {
                this.AnonymousContent.Visibility = Visibility.Visible;
            }
        }

        /// <summary>
        ///     Executes when the user navigates to this page.
        /// </summary>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void loginButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            LoginRegistrationWindow loginWindow = new LoginRegistrationWindow();
            loginWindow.Show();
        }

        private void registerButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            LoginRegistrationWindow loginWindow = new LoginRegistrationWindow();
            loginWindow.Show();
            loginWindow.NavigateToRegistration();
        }
    }
}